package com.swind.fast.modules.app.railway.project.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.swind.fast.common.api.vo.Result;
import com.swind.fast.common.system.query.QueryGenerator;
import com.swind.fast.common.util.oConvertUtils;
import com.swind.fast.common.util.ImportExcelUtil;
import com.swind.fast.modules.app.railway.task.constant.TaskPointStatusEnum;
import com.swind.fast.modules.app.railway.task.entity.RailwayTaskPointFile;
import com.swind.fast.modules.app.railway.project.entity.RailwayProjectTaskPoint;
import com.swind.fast.modules.app.railway.project.entity.RailwayProjectTaskPointAnalyze;
import com.swind.fast.modules.app.railway.project.service.IRailwayProjectTaskPointService;
import com.swind.fast.modules.app.railway.project.service.IRailwayProjectTaskPointAnalyzeService;
import com.swind.fast.modules.app.railway.project.vo.RailwayDataInputVo;
import com.swind.fast.modules.app.railway.task.entity.RailwayTaskPointOperationLog;
import com.swind.fast.modules.app.railway.project.constant.ProjectTestMethodsEnum;

import com.swind.fast.common.system.vo.LoginUser;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/app/railway/project/taskpoint")
@Slf4j
public class RailwayProjectTaskPointController {

    @Autowired
    private IRailwayProjectTaskPointService railwayProjectService;

    @Autowired
    private IRailwayProjectTaskPointAnalyzeService railwayProjectPointAnalyzeService;

    @GetMapping(value = "/list")
    public Result<IPage<RailwayProjectTaskPoint>> queryPageList(RailwayProjectTaskPoint railwayProject,
                                      @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                      @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                      HttpServletRequest req) {

        QueryWrapper<RailwayProjectTaskPoint> queryWrapper = QueryGenerator.initQueryWrapper(railwayProject, req.getParameterMap());
        Page<RailwayProjectTaskPoint> page = new Page<RailwayProjectTaskPoint>(pageNo, pageSize);
        IPage<RailwayProjectTaskPoint> pageList = railwayProjectService.pageMain(page, queryWrapper);
        return Result.OK(pageList);
    }

    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody RailwayProjectTaskPoint railwayProject) {
        // log.info("railwayProject: {}, name: {}", railwayProject, railwayProject.getName());
        railwayProjectService.saveMain(railwayProject);
        // log.info("railwayProject: {}, id: {}, name: {}", railwayProject, railwayProject.getId(), railwayProject.getName());
        // return Result.OK("添加成功！", railwayProject);
        return Result.OK("添加成功！");
    }

    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        RailwayProjectTaskPoint railwayProject = railwayProjectService.getById(id);
        return Result.ok(railwayProject);
    }

    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody RailwayProjectTaskPoint railwayProject) {
        railwayProjectService.updateMainById(railwayProject);
        return Result.OK("编辑成功!");
    }

    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name="id", required=true) String id) {
        railwayProjectService.removeById(id);
        return Result.OK("删除成功!");
    }

    @GetMapping(value = "/point/pics")
    public Result<?> picsAction(@RequestParam(name = "id", required = true) String pointId) {
        List<RailwayTaskPointFile> list = railwayProjectService.getPicsById(pointId);
        return Result.OK("成功!", list);
    }

    @GetMapping(value = "/analyze/get")
    public Result<?> analyzeQueryByIdAction(@RequestParam(name = "id", required = true) String pointId) {
        QueryWrapper<RailwayProjectTaskPointAnalyze> queryWrapper = new QueryWrapper<RailwayProjectTaskPointAnalyze>().eq("point_id", pointId).last("limit 1");
        RailwayProjectTaskPointAnalyze analyzeData = railwayProjectPointAnalyzeService.getOne(queryWrapper);
        return Result.OK("成功!", analyzeData);
    }

    @PostMapping(value = "/analyze/update")
    public Result<?> updateAnalyzeQueryAction(@RequestBody RailwayProjectTaskPointAnalyze railwayProject) {
        Boolean success = railwayProjectPointAnalyzeService.saveOrUpdate(railwayProject);
        return Result.OK("更新!", success);
    }

    @PostMapping(value = "/status/update")
    public Result<?> statusUpdateAction(@RequestBody RailwayTaskPointOperationLog railwayProject) {
        // log.info("railwayProject: {}, name: {}", railwayProject, railwayProject.getName());
        railwayProjectService.updateTestPointStatus(railwayProject);
        return Result.OK("成功！");
    }

    @PostMapping(value = "/duplicate/check")
    public Result<?> dupCheck(@RequestBody RailwayProjectTaskPoint railwayProject) {
        Boolean success = false;
        String id = railwayProject.getId();

        QueryWrapper<RailwayProjectTaskPoint> queryWrapper = new QueryWrapper<RailwayProjectTaskPoint>().eq("project_id", railwayProject.getProjectId()).eq("hole_name", railwayProject.getHoleName().trim()).last("limit 1");
        RailwayProjectTaskPoint task = railwayProjectService.getOne(queryWrapper);
        if (oConvertUtils.isEmpty(task)) {
            return Result.OK("添加成功！", true);
        }

        String pointId = task.getId();
        if (!oConvertUtils.isEmpty(id) && id.equals(pointId)) {
            return Result.OK("添加成功！", true);
        }

        return Result.OK("添加成功！", success);
    }

    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();

        // 错误信息
        List<String> errorMessage = new ArrayList<>();
        int successLines = 0, errorLines = 0;
        String projectId = request.getParameter("projectId");
        log.info("projectId: {}", projectId);

        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);

            try {
                List<RailwayProjectTaskPoint> listRailwayProjectTaskPoints = ExcelImportUtil.importExcel(file.getInputStream(), RailwayProjectTaskPoint.class, params);

                listRailwayProjectTaskPoints.stream().forEach(item -> {
                    item.setProjectId(projectId);
                    item.setStatus(TaskPointStatusEnum.UPLOADED.getValue());
                });

                List<RailwayProjectTaskPoint> inputList = new ArrayList<RailwayProjectTaskPoint>();

                long start = System.currentTimeMillis();

                for (int i = 0; i < listRailwayProjectTaskPoints.size(); i++) {
                    RailwayProjectTaskPoint sysTaskExcel = listRailwayProjectTaskPoints.get(i);
                    log.info("taskpoint: {}", sysTaskExcel);

                    if (!oConvertUtils.isEmpty(sysTaskExcel.getHoleName().trim())) {
                        QueryWrapper<RailwayProjectTaskPoint> queryWrapper = new QueryWrapper<RailwayProjectTaskPoint>().eq("project_id", projectId).eq("hole_name", sysTaskExcel.getHoleName().trim());
                        Integer count = railwayProjectService.count(queryWrapper);
                        if (count < 1) {
                            String testMethod = sysTaskExcel.getTestMethod();
                            ProjectTestMethodsEnum item = ProjectTestMethodsEnum.getByName(testMethod);
                            if (!oConvertUtils.isEmpty(item)) {
                                Integer testMethodDict = item.getValue();
                                sysTaskExcel.setTestMethodDict(testMethodDict);
                            }

                            inputList.add(sysTaskExcel);
                        } else {
                            log.info("holeName duplicate: {}", sysTaskExcel.getHoleName().trim());
                        }
                    }
                }

                railwayProjectService.saveBatch(inputList);
                log.info("导入消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                successLines = listRailwayProjectTaskPoints.size();

            } catch (Exception e) {
                errorMessage.add("发生异常：" + e.getMessage());
                log.error(e.getMessage(), e);

            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }

        return ImportExcelUtil.imporReturnRes(errorLines, successLines, errorMessage);
    }

    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(RailwayProjectTaskPoint workTask, HttpServletRequest request) {
        // Step.1 组装查询条件
        QueryWrapper<RailwayProjectTaskPoint> queryWrapper = QueryGenerator.initQueryWrapper(workTask, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //[03]用户导出，如果选择数据则只导出相关数据--------------------
        String selections = request.getParameter("selections");
        if (!oConvertUtils.isEmpty(selections)) {
            queryWrapper.in("id", selections.split(","));
        }
        //[03]用户导出，如果选择数据则只导出相关数据----------------------
        List<RailwayProjectTaskPoint> pageList = railwayProjectService.list(queryWrapper);

        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "工作实验点");
        mv.addObject(NormalExcelConstants.CLASS, RailwayProjectTaskPoint.class);
        // LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // ExportParams exportParams = new ExportParams("工作点数据", "导出人:"+user.getRealname(), "导出信息");
        ExportParams exportParams = new ExportParams();
        // exportParams.setImageBasePath(upLoadPath);
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    @RequestMapping(value = "/parseExcel", method = RequestMethod.POST)
    public Result<?> parseExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();

        // 错误信息
        List<String> errorMessage = new ArrayList<>();
        int successLines = 0, errorLines = 0;
        List<RailwayDataInputVo> retListRailwayDataInputVos = new ArrayList<RailwayDataInputVo>();
        String dataStr = "";

        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue(); // 获取上传文件对象
            log.info("file: {}, name: {}", file, file.getOriginalFilename());
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);

            try {

                List<RailwayDataInputVo> listRailwayDataInputVos = ExcelImportUtil.importExcel(file.getInputStream(), RailwayDataInputVo.class, params);
                for (int i = 0; i < listRailwayDataInputVos.size(); i++) {
                    RailwayDataInputVo sysTaskExcel = listRailwayDataInputVos.get(i);
                    log.info("task: {}", sysTaskExcel);
                    if (oConvertUtils.isEmpty(sysTaskExcel.getQc())) {
                        break;
                    } else {
                        dataStr += String.format("%s,%s,%s|", sysTaskExcel.getDepth(), sysTaskExcel.getQc(), sysTaskExcel.getFs());
                        retListRailwayDataInputVos.add(sysTaskExcel);
                        successLines++;
                    }
                }

                long start = System.currentTimeMillis();
                log.info("导入消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                // successLines = listRailwayDataInputVos.size();

            } catch (Exception e) {
                errorMessage.add("发生异常：" + e.getMessage());
                log.error(e.getMessage(), e);

            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        Map<String, Object> result = new HashMap();
        result.put("dataArray", retListRailwayDataInputVos);
        result.put("dataStr", dataStr);

        // return ImportExcelUtil.imporReturnRes(errorLines, successLines, errorMessage);
        return Result.OK("查看详情!", result);
    }
}
